﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace WechatMul
{
    internal class WechatHelper
    {
        static string _windowTitle = string.Empty;
        static List<IntPtr> _windowHandles = new List<IntPtr>();

        const uint SWP_NOZORDER = 0x0004;
        const uint SWP_NOACTIVATE = 0x0010;

        [DllImport("user32.dll", SetLastError = true)]
        static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);

        [DllImport("user32.dll")]
        static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);

        [DllImport("user32.dll")]
        static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);

        delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);

        public static void ExecApplication(string filePath, int count = 2, string title = "微信")
        {
            _windowTitle = title;
            WriteBatFile(filePath, count);

            Process proc = null;
            try
            {
                proc = new Process();
                proc.StartInfo.WorkingDirectory = Application.UserAppDataPath;
                proc.StartInfo.FileName = "mul.bat";
                proc.StartInfo.CreateNoWindow = false;
                proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;//这里设置DOS窗口不显示，经实践可行
                proc.Start();
                proc.WaitForExit();

                Thread.Sleep(500);
                TitleForms();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception Occurred :{0},{1}", ex.Message, ex.StackTrace.ToString());
            }
        }

        private static void WriteBatFile(string wechatPath, int count)
        {
            var script = new StringBuilder();

            for (int i = 0; i < count; i++)
            {
                script.AppendLine(" start \"\" \"" + wechatPath + "\"\r\n ");
            }

            var filePath = System.IO.Path.Combine(Application.UserAppDataPath, "mul.bat");
            System.IO.File.WriteAllText(filePath, script.ToString());
        }

        private static void TitleForms()
        {
            _windowHandles.Clear();
            EnumWindows(new EnumWindowsProc(EnumAllWindows), IntPtr.Zero);

            var space = 5;
            var clientWidth = 280;
            var clientHeight = 380;

            var useWidth = 0;
            if ((clientWidth + space) * _windowHandles.Count < Screen.PrimaryScreen.WorkingArea.Width)
                useWidth = (clientWidth + space) * _windowHandles.Count;
            else
                while (useWidth + clientWidth + space < Screen.PrimaryScreen.WorkingArea.Width)
                {
                    useWidth += clientWidth + space;
                }

            var lines = (int)Math.Ceiling((clientWidth + space) * _windowHandles.Count / (decimal)useWidth);
            var useHeigh = lines * clientHeight + space * (lines - 1);

            var position = new Point();
            position.X = (Screen.PrimaryScreen.WorkingArea.Width - useWidth) / 2;
            position.Y = (Screen.PrimaryScreen.WorkingArea.Height - useHeigh) / 2;

            int x = position.X;
            int y = position.Y;
            int line = 1;
            foreach (IntPtr hWnd in _windowHandles)
            {
                SetWindowPos(hWnd, IntPtr.Zero, x, y, clientWidth, clientHeight, SWP_NOZORDER | SWP_NOACTIVATE);

                if (x + (clientWidth + space) * 2 >= Screen.PrimaryScreen.WorkingArea.Width)
                {
                    x = position.X;
                    y = position.Y + (clientHeight + space) * line;
                    line++;
                }
                else x += clientWidth + space;
            }
        }

        private static bool EnumAllWindows(IntPtr hWnd, IntPtr lParam)
        {
            const int nChars = 256;
            var buff = new StringBuilder(nChars);

            if (GetWindowText(hWnd, buff, nChars) > 0)
            {
                if (buff.ToString() == _windowTitle)
                {
                    // 添加到窗口句柄列表  
                    _windowHandles.Add(hWnd);
                }
            }

            return true; // 继续枚举下一个窗口  
        }
    }
}
